/*
 * gx_os_utils.c
 *
 *  Created on: Apr 8, 2012
 *      Author: zhanggx
 */
#include <stdlib.h>

#include <errno.h>
#include "gx_os_utils.h"


int
safe_read_n(int fd, char* buf, size_t count) {
	int nleft, nread;

	nleft = count;
	char* ptr = buf;
	while(nleft > 0) {
		nread = read(fd, ptr, nleft);
		if (nread == -1) {
			if (errno == EINTR) {
				continue;
			}
			else{
				return -1;
			}
		}
		else if (nread == 0) {
			//read to end?
			break;
		}
		nleft -= nread;
		ptr	   += nread;
	}
	return (count - nleft);
}

int
safe_write_n(int fd, char* buf, size_t count) {
	int nleft, nread;

	nleft = count;
	char* ptr = buf;
	while(nleft > 0) {
		nread = write(fd, ptr, nleft);
		if (nread == -1) {
			if (errno == EINTR) {
				continue;
			}
			else{
				return -1;
			}
		}
		else if (nread == 0) {
			//read to end?
			break;
		}
		nleft -= nread;
		ptr	   += nread;
	}
	return (count - nleft);
}

void*
gx_malloc(size_t count) {
	return malloc(count);
}

void
gx_free(void* ptr) {
	free(ptr);
}
